package com.edu.filter;

import com.edu.dto.ResultDto;
import com.edu.utils.JwtUtils;
import com.edu.utils.ReturnCode;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * com.edu.filter
 * 2024/7/2 23:44
 *
 * @author Fancy
 * @version 1.0
 */
@WebFilter(urlPatterns = "/*")
public class LoginControllerFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest ) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String requestURI = request.getRequestURI();
        if(requestURI.contains("login")){
            //如果跳转到登录就放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(requestURI.contains("register")){
            // 如果为注册请求，则直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String token = request.getHeader("token");

        if(token == null){
            String loginError = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "未登录");
            //返回信息给客户端
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(loginError);
            return;
        }

        if(JwtUtils.validateToken(token) == null){
            //令牌存在问题
            String loginError = ResultDto.fail(ReturnCode.UNAUTHORIZED.getCode(), "token无效");
            //返回信息给客户端
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write(loginError);
            return;
        }

        String newToken = JwtUtils.refreshAndResetToken(token);
        response.setHeader("token", newToken);
        System.out.println(newToken);
        filterChain.doFilter(request,response);
    }
}
